const gulp = require('gulp');
const babel = require('gulp-babel');
const fileinclude = require('gulp-file-include');
const sass = require('gulp-sass')(require('sass'));
const borwserync = require('browser-sync').create();
const del = require('del');

gulp.task('html', async () => {
    gulp.src('./src/*.html')
        .pipe(fileinclude({
            prefix: '@@',
            basepath: '@file'
        }))
        .pipe(gulp.dest("./dist"))
});
gulp.task('scss', async () => {
    gulp.src(['./src/scss/*.scss'])
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest('./dist/css'));
});
gulp.task('js', async () => {
    gulp.src(['./src/javascripts/*.js'])
        .pipe(babel({
            presets: ["@babel/preset-env"]
        }))
        .pipe(gulp.dest('./dist/javascripts'))
})

function browserSyncReload(done) {
    borwserync.reload();
    done();
}
gulp.task('watch', async () => {
    gulp.watch(["./src/**/*.html"], gulp.series("html", browserSyncReload));
    gulp.watch(["./src/javascripts/*.js"], gulp.series("js", browserSyncReload));
    gulp.watch(["./src/scss/*.scss"], gulp.series("scss", browserSyncReload));
})

gulp.task('browsersync', async () => {
    borwserync.init({
        server: {
            baseDir: './'
        },
        port: 8080,
    })
})

function clearDir(done) {
    del(['./dist/**/*']);
    setTimeout(() => {
        done()
    }, 1000);
}

let build = gulp.series(clearDir, 'html', 'scss', 'js', 'watch', 'browsersync');

exports.build = build;